package cn.fl.mcr.service.impl;

import cmm.mid.core.framework.dto.DataResultDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrContractService;
import cn.fl.mcr.transform.McrBillMVOTransform;
import cn.fl.mcr.vo.McrBillMVO;
import cn.fl.mcr.vo.McrContractExcelVO;
import cn.lb.framework.poi.excel.ExcelImportUtil;
import cn.lb.framework.poi.excel.entity.ImportParams;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrLoanAccountQC;
import cn.lionbridgecapital.loan.model.constant.McrContractConstant;
import cn.lionbridgecapital.loan.model.dto.McrBillMDTO;
import cn.lionbridgecapital.loan.model.dto.McrLoanAccountDTO;
import cn.lionbridgecapital.loan.service.api.IMcrBillMApiService;
import cn.lionbridgecapital.loan.service.api.IMcrContractApiService;
import cn.lionbridgecapital.loan.service.api.IMcrLoanAccountApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @Author: YangXin
 * @Description: 小贷合同管理Service实现类
 * @CreateTime: 2019/12/17 14:31
 * @Version: 1.0.0
 */
@Service
public class McrContractServiceImpl implements IMcrContractService {

    private static final Logger logger = LoggerFactory.getLogger(McrContractServiceImpl.class);

    @Autowired
    private IMcrContractApiService mcrContractApiService;
    @Autowired
    private IMcrBillMApiService publicMcrBillMApiService;
    @Autowired
    private IMcrLoanAccountApiService publicMcrLoanAccountApiService;

    /**
     * 补录小贷仲裁合同
     * @param realPath excel路径
     * @return success 1.成功  0.失败
     * @throws BaseException 异常
     */
    @Override
    public DataResultDTO importData(String realPath,String arbitrateType) throws BaseException {
        final String methodName = "importData";
        if (StringUtils.isEmpty(realPath)){
            BaseLogUtils.error(logger,methodName,"补录小贷仲裁合同.未获取到Excel路径");
            throw new BaseException(BaseExceptionConstant.COMMON_0002,"未获取到Excel路径");
        }
        DataResultDTO resultDTO = new DataResultDTO(BaseConstant.IS_YESNO_YES, "补录小贷仲裁合同成功");
        int i = 0;
        StringBuilder errorString = new StringBuilder();
        try{
            List<McrContractExcelVO> mcrCustomerVOList = this.importXls(realPath);
            if (CollectionUtils.isNotEmpty(mcrCustomerVOList)){
                for (McrContractExcelVO mcrContractExcelVO : mcrCustomerVOList) {
                    i++;
                    String cstId = mcrContractExcelVO.getCstId();
                    String loanCrCntNo = mcrContractExcelVO.getLoanCrCntNo();
                    BaseLogUtils.info(logger,methodName,
                            "补录小贷仲裁合同.请求参数.cstId:"+cstId+",loanCrCntNo:"+loanCrCntNo);
                    DataResultDTO arbitrateContractDTO =
                            this.mcrContractApiService.additionalArbitrateContract(Long.parseLong(cstId), loanCrCntNo,arbitrateType);
                    BaseLogUtils.info(logger,methodName,
                            "补录小贷仲裁合同.补录结果.cstId:"+cstId+",result:" +JSONObject.toJSONString(arbitrateContractDTO));
                    if (null == arbitrateContractDTO || BaseConstant.IS_YESNO_YES != arbitrateContractDTO.getSuccess()){
                        errorString.append("第").append(i).append("行补录小贷仲裁合同失败</br>");
                    }
                }
            }
            if (errorString.length() > 0 ){
                resultDTO.setInfo(errorString.toString());
                resultDTO.setSuccess(BaseConstant.IS_YESNO_NO);
            }
        }catch (BaseException ex){
            BaseLogUtils.error(logger,methodName,"补录小贷仲裁合同.异常.ex:"+ex.getMessage(),ex);
            throw new BaseException(BaseExceptionConstant.COMMON_0002,ex.getMessage());
        }catch (Exception ex){
            BaseLogUtils.error(logger,methodName,"补录小贷仲裁合同.异常.ex:"+ex.getMessage(),ex);
            throw new BaseException(BaseExceptionConstant.COMMON_0002,"补录小贷仲裁合同异常");
        }
        BaseLogUtils.info(logger,methodName,"补录小贷仲裁合同.最终返回参数.result:"+ JSONObject.toJSONString(resultDTO));
        return resultDTO;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Pager searchMcrBillMListPage(Pager page) throws BaseException {
        final String methodName = "searchMcrBillMListPage";
        if(null == page.getCondition()){
            BaseLogUtils.info(logger,methodName,"签署合同获取小贷账单.参数异常");
            throw new BaseException(BaseExceptionConstant.COMMON_0002,"签署合同获取小贷账单.参数异常");
        }
        Pager pager;
        try{
            // 根据条件进行分页查询
            pager = this.publicMcrBillMApiService.searchMcrBillMListPage(page);
            if (CollectionUtils.isEmpty(pager.getResultList())){
                BaseLogUtils.info(logger,methodName,"签署合同获取小贷账单.未获取到searchListPage数据");
                return pager;
            }

            List<McrBillMDTO> list = (List<McrBillMDTO>) pager.getResultList();
            List<McrBillMVO> mcrBillMVOS = McrBillMVOTransform.toVOList(list);

            // 查询放款渠道
            McrLoanAccountQC mcrLoanAccountQC = new McrLoanAccountQC();
            mcrLoanAccountQC.setIsValid(BaseConstant.IS_YESNO_YES);
            mcrLoanAccountQC.setIsDel(BaseConstant.IS_YESNO_NO);
            List<McrLoanAccountDTO> mcrLoanAccountDTOList =
                    this.publicMcrLoanAccountApiService.searchMcrLoanAccountDTOList(mcrLoanAccountQC);

            // 获取放款类型
            if (CollectionUtils.isNotEmpty(mcrLoanAccountDTOList) && CollectionUtils.isNotEmpty(mcrBillMVOS)){
                continueOut:
                for (McrBillMVO mcrBillMVO : mcrBillMVOS) {
                    for (McrLoanAccountDTO mcrLoanAccountDTO : mcrLoanAccountDTOList) {
                        if (StringUtils.isNotEmpty(mcrBillMVO.getLoanAccountId())){
                            // 判断账单所对应资方信息
                            if (mcrLoanAccountDTO.getId().equals(mcrBillMVO.getLoanAccountId()) && StringUtils.isNotEmpty(mcrLoanAccountDTO.getContCfgCd())){
                                mcrBillMVO.setContractTypeCd(mcrLoanAccountDTO.getContCfgCd());
                                continue continueOut;
                            }
                        }else{
                            // 我司放款
                            mcrBillMVO.setContractTypeCd(McrContractConstant.CFG_CD_CON002);
                        }
                        continue continueOut;
                    }
                }
            }
            pager.setResultList(mcrBillMVOS);

        }catch (BaseException ex){
            BaseLogUtils.error(logger,methodName,"签署合同获取小贷账单.异常.ex:"+ex.getMessage(),ex);
            throw new BaseException(BaseExceptionConstant.COMMON_0002,ex.getMessage());
        }catch (Exception ex){
            BaseLogUtils.error(logger,methodName,"签署合同获取小贷账单.异常.ex:"+ex.getMessage(),ex);
            throw new BaseException(BaseExceptionConstant.COMMON_0002,"签署合同获取小贷账单异常");
        }
        return pager;
    }

    /**
     * 获取Excel文件
     * @param filePath 文件地址
     * @return 文件参数
     * @throws BaseException 业务数据
     */
    private List<McrContractExcelVO> importXls(String filePath) throws BaseException {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "importXls", "小贷系统导入Excel：realPath:"+filePath, CurrentThreadContext.getCurrentUserName());
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//标题占用行数
        params.setHeadRows(1);//表头占用行数
        params.setNeedSave(false);//是否保存文件

        List<McrContractExcelVO> list = null;
        File file = new File(filePath);
        if (file.exists()) {
            BaseLogUtils.info(logger, "importXls", "小贷系统导入Excel.文件存在");
            list = ExcelImportUtil.importExcel(file, McrContractExcelVO.class, params);
        }
        BaseLogUtils.info(logger, "importXls", "小贷系统导入Excel:" + JSON.toJSONString(list));
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "importXls", "导入帐号.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return list;
    }
}
